package com.tamo.ppresta.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.tamo.ppresta.util.AppManager;
import com.tamo.ppresta.util.Event;
import com.tamo.ppresta.util.EventBusUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.tamo.ppresta.constant.APP_CONSTANT.APP_NAME;

/**
 * @author yeyang
 * @name ppresta
 * @class name：com.tamo.ppresta.base
 * @class describe
 * @time 2022/12/18 14:27
 * @change
 * @chang time
 * @class describe
 */
public abstract  class BaseAppCompatActivity extends AppCompatActivity implements View.OnClickListener {
    //获取TAG的activity名称
    protected final String TAG = this.getClass().getSimpleName();
    //是否显示标题栏
    private boolean isShowTitle = true;
    //是否显示状态栏
    private boolean isShowStatusBar = true;
    private Unbinder unbinder;
    //封装Toast对象
    private static Toast toast;
    public Context context;
    //是否允许旋转屏幕
    private boolean isAllowScreenRoate = true;
    /**
     * 是否输出日志信息
     **/
    private boolean isDebug;
    private BaseApplication baseApplication;
    private Bundle bundle;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //不显示标题栏
        if (!isShowTitle) {
            supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        //设置是否显示状态栏
        if (!isShowStatusBar) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
                    , WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        super.onCreate(savedInstanceState);
        setContentView(setLayout());
        context = this;
        bundle = getIntent().getExtras();
        unbinder = ButterKnife.bind(this);
        if (isRegisterEventBus()) {
            EventBusUtil.register(this);
        }
        baseApplication = (BaseApplication) getApplication();
        isDebug = baseApplication.isDebug;
        //activity管理
        AppManager.getAppManager().addActivity(this);


        //设置屏幕是否可旋转
        if (!isAllowScreenRoate) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }


        setView();
        setData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
        if (isRegisterEventBus()) {
            EventBusUtil.unregister(this);
        }
        //将Activity实例从AppManager的堆栈中移除
        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        SharedPreferences sharedPreferences = getSharedPreferences(SaveAPPData.UPDATE_APP_IS_SHOW, MODE_PRIVATE);
//        String isShowDialog = sharedPreferences.getString(SaveAPPData.DIALOG_APP_IS_SHOW, null);
////        Log.i("sdfjskfsjfsf","打开标志数据"+isShowDialog+"结尾数据");
//        if (TextUtils.isEmpty(isShowDialog)) {
//            //检测更新版本信息
//            new getVistionUtil(BaseAppCompatActivity.this, Api.VERSION).checkUpdate(false, 1);
//            SaveAPPData saveAPPData = new SaveAPPData();
//            saveAPPData.SaveUpdateialogIsShow(BaseAppCompatActivity.this, "111");
//        }
    }


    /**
     * 绑定布局
     *
     * @return
     */
    protected abstract int setLayout();

    /**
     * 初始化组件
     */
    protected abstract void setView();

    /**
     * 设置数据等逻辑代码
     */
    protected abstract void setData();

    /**
     * 简化findViewById()
     *
     * @param resId
     * @param <T>
     * @return
     */
    protected <T extends View> T fvbi(int resId) {
        return (T) findViewById(resId);
    }

    /**
     * Intent跳转
     *
     * @param context
     * @param clazz
     */
    protected void toClass(Context context, Class<? extends BaseAppCompatActivity> clazz) {
        toClass(context, clazz, null);
    }

    /**
     * Intent带值跳转
     *
     * @param context
     * @param clazz
     * @param bundle
     */
    protected void toClass(Context context, Class<? extends BaseAppCompatActivity> clazz, Bundle bundle) {
        Intent intent = new Intent(context, clazz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 带返回值的跳转
     *
     * @param context
     * @param clazz
     * @param bundle
     * @param reuqestCode
     */
    protected void toClass(Context context, Class<? extends BaseAppCompatActivity> clazz, Bundle bundle, int reuqestCode) {
        Intent intent = new Intent(context, clazz);
        intent.putExtras(bundle);
        startActivityForResult(intent, reuqestCode);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusCome(Event event) {
        if (event != null) {
            receiveEvent(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onStickyEventBusCome(Event event) {
        if (event != null) {
            receiveStickyEvent(event);
        }
    }

    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

    /**
     * 接收到分发到事件
     * Activity中复写receiveEvent(Event event)或receiveStickyEvent(Event event)来处理接收到事件后的逻辑
     *
     * @param event 事件
     */
    protected void receiveEvent(Event event) {

    }

    /**
     * 接受到分发的粘性事件
     * Activity中复写receiveEvent(Event event)或receiveStickyEvent(Event event)来处理接收到事件后的逻辑
     *
     * @param event 粘性事件
     */
    protected void receiveStickyEvent(Event event) {

    }

    /**
     * 保证同一按钮在1秒内只会响应一次点击事件
     */
    public abstract class OnSingleClickListener implements View.OnClickListener {
        //两次点击按钮之间的间隔，目前为1000ms
        private static final int MIN_CLICK_DELAY_TIME = 1000;
        private long lastClickTime;

        public abstract void onSingleClick(View view);

        @Override
        public void onClick(View view) {
            long curClickTime = System.currentTimeMillis();
            if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
                lastClickTime = curClickTime;
                onSingleClick(view);
            }
        }
    }

    /**
     * 同一按钮在短时间内可重复响应点击事件
     */
    public abstract class OnMultiClickListener implements View.OnClickListener {
        public abstract void onMultiClick(View view);

        @Override
        public void onClick(View v) {
            onMultiClick(v);
        }
    }

    /**
     * 显示提示  toast
     *
     * @param msg 提示信息
     */
    @SuppressLint("ShowToast")
    public void showToast(String msg) {
        try {
            if (null == toast) {
                toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
            } else {
                toast.setText(msg);
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    toast.show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            //解决在子线程中调用Toast的异常情况处理
            Looper.prepare();
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
            Looper.loop();
        }
    }


    /**
     * 隐藏软键盘
     */
    public void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null && null != imm) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 显示软键盘
     */
    public void showSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null && null != imm) {
            imm.showSoftInputFromInputMethod(getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 是否允许屏幕旋转
     * onCreate 设置一定要在 super.onCreate(savedInstanceState) 方法之前设置
     *
     * @param allowScreenRoate true or false
     */
    public void setAllowScreenRoate(boolean allowScreenRoate) {
        isAllowScreenRoate = allowScreenRoate;
    }

    /**
     * 设置是否显示标题栏
     * onCreate 设置一定要在 super.onCreate(savedInstanceState) 方法之前设置
     *
     * @param showTitle true or false
     */
    public void setShowTitle(boolean showTitle) {
        isShowTitle = showTitle;
    }

    /**
     * 设置是否显示状态栏
     * onCreate 设置一定要在 super.onCreate(savedInstanceState) 方法之前设置
     *
     * @param showStatusBar true or false
     */
    public void setShowStatusBar(boolean showStatusBar) {
        isShowStatusBar = showStatusBar;
    }

    long firstTime = 0;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {     //KEYCODE_BACK：回退键
            if (AppManager.getActivityStack() != null && AppManager.getActivityStack().size() == 1) {// 判断堆栈集合 并且长度为1时 执行推出app
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {
                    Toast.makeText(AppManager.getAppManager().getTopActivity(), "再按一次退出app", Toast.LENGTH_SHORT).show();
                    firstTime = System.currentTimeMillis();
                    return true;
                } else {
                    AppManager.getAppManager().appExit();
                }
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * [日志输出]
     *
     * @param msg
     */
    protected void $Log(String msg) {
        if (isDebug) {
            Log.d(APP_NAME, msg);
        }
    }

    /**
     * [防止快速点击]
     *
     * @return
     */
    private long lastClick = 0;

    private boolean fastClick() {
        if (System.currentTimeMillis() - lastClick <= 1000) {
            return false;
        }
        lastClick = System.currentTimeMillis();
        return true;
    }


    /**
     * 判断是否安装拼多多
     *
     * @param
     * @param pkgName
     * @return
     */
    public boolean checkHasInstalledApp(String pkgName) {

        PackageManager pm = getPackageManager();

        boolean app_installed;

        try {

            pm.getPackageInfo(pkgName, PackageManager.GET_GIDS);

            app_installed = true;

        } catch (PackageManager.NameNotFoundException e) {

            app_installed = false;

        } catch (RuntimeException e) {

            app_installed = false;

        }

        return app_installed;

    }
}